/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp;

import android.os.AsyncTask;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;

public class SwipeTabListener 
			extends 
				TabListener 
			implements 
				com.actionbarsherlock.app.ActionBar.TabListener, 
				ViewPager.OnPageChangeListener {
	
	private int mainPosition;
	private ViewPager pager;
	
	public SwipeTabListener(
			BaseActivity activity, int tabContainer, String tag, 
			Class<? extends SherlockFragment> fragmentClass, 
			int mainPosition, int size) {
		
		super(activity, tabContainer, tag, fragmentClass);
		this.mainPosition = mainPosition;
	}

//	@Override
//	public void onTabSelected(Tab tab, FragmentTransaction ft) {
//		final int pos = tab.getPosition()-mainPosition;
//		if(mActivity.getPreviousListener()!=this)
//			super.onTabSelected(tab, ft);
//		
//		new AsyncTask<Integer, Void, String>() {
//
//			@Override
//			protected String doInBackground(Integer... params) {
//				try {
//					Thread.sleep(250);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//				return "OK";
//			}
//			
//			protected void onPostExecute(String result) {
//				if(pager!=null && pos!=pager.getCurrentItem())
//					pager.setCurrentItem(pos);
//			};
//			
//		}.execute(pos);
//	}
//	
//	@Override
//	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
//		mActivity.setPreviousListener(this);
//	}
//	
//	@Override
//	public void onUnselectPrevious(FragmentTransaction ft) {
//		super.onTabUnselected(getTab(), ft);
//	}
	
	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		
	}

	@Override
	public void onPageSelected(int position) {
		int old = mActivity.getSupportActionBar().getSelectedNavigationIndex();
		if(old!=position)
			mActivity.getSupportActionBar().setSelectedNavigationItem(position);
	}
	
	public void setPager(ViewPager pager) {
		this.pager = pager;
		pager.setOnPageChangeListener(this);
	}
	
	@Override
	protected SherlockFragment newFragment() {
		super.newFragment();
		((SwipeFragment) mFragment).setTabListener(this);
		return mFragment;
	}
}
